/**
 * This file is part of Wasagent.
 *
 * Wasagent is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Wasagent is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Wasagent. If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package net.wait4it.wasagent.tests;

import javax.management.ObjectName;

import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.pmi.stat.WSJTAStats;
import com.ibm.websphere.pmi.stat.WSStats;

import net.wait4it.wasagent.jmx.JmxService;
import net.wait4it.wasagent.utils.Result;
import net.wait4it.wasagent.utils.Status;

/**
 * @author Yann Lambret
 *
 */
public class TransactionServiceTest extends TestUtils implements Test {

	private static final String message = "jta test";
	private static final String query = "WebSphere:type=TransactionService,*";

	public Result run(AdminClient client, ObjectName perfMbean, String params) {
		Result result = new Result();
		StringBuilder output = new StringBuilder();
		int code = 0;

		/**
		 * Specific test variables
		 */
		ObjectName mbean;
		WSStats stats;
		long activeCount;
		long warning;
		long critical;

		/**
		 * Parse parameters
		 */
		String[] paramsArray = params.split(";");
		warning = Long.parseLong(paramsArray[1]);
		critical = Long.parseLong(paramsArray[2]);

		try {
			mbean = JmxService.getMbean(client, query);
			stats = JmxService.getStats(client, perfMbean, mbean);
			activeCount = getCountStats(stats, WSJTAStats.ActiveCount).getCount();
			output.append("jta-activeCount=").append(activeCount);
			code = checkResult(activeCount, critical, warning, code);
		} catch (Exception e) {
			result.setStatus(Status.UNKNOWN);
			result.setMessage(Status.UNKNOWN.getMessage(message));
			return result;
		}

		for (Status status : Status.values()) {
			if (code == status.getCode()) {
				result.setStatus(status);
				result.setMessage(status.getMessage(message));
				result.setOutput(output.toString());
				break;
			}
		}

		return result;
	}

}
